package com.sds.sweng.swat.miplatform.ui.design.utils;

import java.util.List;

import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.map.jsontype.impl.StdSubtypeResolver;
import org.codehaus.jackson.mrbean.AbstractTypeMaterializer;

import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformComponent;
import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformDesignModel;
import com.sds.sweng.swat.miplatform.ui.design.palettes.FavoriteBean;
import com.sds.sweng.swat.miplatform.ui.design.palettes.FavoriteList;

public class ModelUtils {

	private static ObjectMapper mapper = new ObjectMapper();

	static {
		AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
		StdSubtypeResolver subtypeResolver = new StdSubtypeResolver();

		mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
		mapper.getSerializationConfig().setAnnotationIntrospector(introspector);

		mapper.getDeserializationConfig().setSubtypeResolver(subtypeResolver);
		mapper.getSerializationConfig().setSubtypeResolver(subtypeResolver);

		mapper.getDeserializationConfig().setAbstractTypeResolver(new AbstractTypeMaterializer());
	}

	public static byte[] toJsonModel(MiplatformDesignModel model) throws Exception {
		return mapper.writeValueAsBytes(model);
	}

	public static MiplatformDesignModel loadModel(byte[] input) throws Exception {
		return mapper.readValue(input, 0, input.length, MiplatformDesignModel.class);
	}

	public static String toJsonModel(MiplatformComponent model) throws Exception {
		return mapper.writeValueAsString(model);
	}

	public static MiplatformComponent loadModel(String input) throws Exception {
		return mapper.readValue(input, MiplatformComponent.class);
	}

	public static List<FavoriteBean> loadFavorites(String storedValue) throws Exception {
		return ((FavoriteList) mapper.readValue(storedValue, FavoriteList.class)).getFavorites();
	}

	public static String toJsonFavorites(List<FavoriteBean> favorites) throws Exception {
		return mapper.writeValueAsString(new FavoriteList(favorites));
	}

}
